package com.admin.system.modules.mnt.service.impl;

import cn.hutool.core.util.IdUtil;
import com.admin.system.modules.mnt.dto.DeployHistoryQueryDTO;
import com.admin.system.modules.mnt.entity.DeployHistory;
import com.admin.system.modules.mnt.mapper.DeployHistoryMapper;
import com.admin.system.modules.mnt.service.DeployHistoryService;
import com.admin.common.utils.DateUtil;
import com.admin.common.utils.PageResult;
import com.admin.common.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author sq-lan
 */
@Service
@RequiredArgsConstructor
public class DeployHistoryServiceImpl extends ServiceImpl<DeployHistoryMapper, DeployHistory> implements DeployHistoryService {

    @Override
    public PageResult<DeployHistory> paging(DeployHistoryQueryDTO dto) {
        PageHelper.startPage(dto.getCurrent(), dto.getSize());
        List<DeployHistory> list = this.list(dto);
        return PageUtil.toPageHelper(list);
    }

    @Override
    public List<DeployHistory> list(DeployHistoryQueryDTO dto) {
        LambdaQueryWrapper<DeployHistory> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.hasText(dto.getBlurry())) {
            wrapper.and(w -> w.like(DeployHistory::getAppName, dto.getBlurry())
                    .or().like(DeployHistory::getIp, dto.getBlurry())
                    .or().like(DeployHistory::getDeployUser, dto.getBlurry()));
        }
        if (dto.getDeployDate() != null && !dto.getDeployDate().isEmpty()) {
            wrapper.between(DeployHistory::getDeployDate, dto.getDeployDate().get(0), dto.getDeployDate().get(1));
        }
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(DeployHistory entity) {
        entity.setId(IdUtil.simpleUUID());
        entity.setDeployDate(DateUtil.getTimeStamp());
        save(entity);
    }

}
